package com.hengqin.macao.utils;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;

import com.hengqin.macao.activity.HProgressBarLoading;
import com.hengqin.macao.activity.WebActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MyWebChromeClient extends WebChromeClient {
    private WebActivity activity;
    private ValueCallback<Uri[]> filePathCallback;
    private Uri cameraTakePhotoTargetUri;
    private boolean isContinue=false;

    public MyWebChromeClient(WebActivity activity) {
        this.activity = activity;
    }

    @Override
    public void onReceivedTitle(WebView view, String title)
    {
        super.onReceivedTitle(view, title);
        // 截获404，500等错误
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
        {
            if (title.contains("404") || title.contains("500") || title.contains("Error"))
            {
                //                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                //                    view.loadUrl(mErrorUrl);
                activity.errorOperation();
            }
        }
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        System.out.println("newProgress:"+newProgress);
        //如果没有网络直接跳出方法
        if (!MyUtils.isNetworkAvailable(activity)) {
            return;
        }
        //如果进度条隐藏则让它显示
        if (View.INVISIBLE == activity.mTopProgress.getVisibility()) {
            activity.mTopProgress.setVisibility(View.VISIBLE);
        }
        //大于80的进度的时候,放慢速度加载,否则交给自己加载
        if (newProgress >= 80) {
            //拦截webView自己的处理方式
            if (isContinue) {
                return;
            }
            activity.mTopProgress.setCurProgress(100, 3000, new HProgressBarLoading.OnEndListener() {
                @Override
                public void onEnd() {
                    activity.finishOperation(true);
                    isContinue = false;
                }
            });

            isContinue = true;
        } else {
            activity.mTopProgress.setNormalProgress(newProgress);
        }
    }

    @Override
    public boolean onJsAlert(WebView view, String url, String message,
                             JsResult result) {
        Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
        result.confirm();
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
        this.filePathCallback = filePathCallback;
        if (fileChooserParams.isCaptureEnabled()) {
            checkCamerPermission();
        } else {
            openChooserActivity(fileChooserParams.createIntent());
        }
        return true;
    }

    private void checkCamerPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //弹出对话框接收权限
                ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, WebActivity.FILE_CAMERA_REQUEST_PERMISSION);
            } else {
                takePicture();
            }
        } else {
            takePicture();
        }
    }

    public void takePicture() {
        //调用系统相机
        Intent intentCamera = new Intent();
        intentCamera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intentCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        this.cameraTakePhotoTargetUri = getTempUri();
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, cameraTakePhotoTargetUri);

        activity.startActivityForResult(intentCamera, WebActivity.CAMERA_REQUEST);
    }

    private Uri getTempUri() {
        // Create an image file name
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String dt = sdf.format(new Date());
        File imageFile = null;
        String doc = Environment.getExternalStorageDirectory()
                + "/" + activity.getPackageName();
        imageFile = new File(doc, "Camera_" + dt + ".jpg");
        File file = new File(doc);
        if (!file.exists()) {
            file.mkdir();
        }
        Uri imageUri = Uri.fromFile(imageFile);

        /*获取当前系统的android版本号*/
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion < 24) {
            return imageUri;
        } else {
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            return uri;
        }
    }

    private void openChooserActivity(Intent intent) {
        //调用自己的图库
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        activity.startActivityForResult(intent, WebActivity.FILE_CHOOSER_RESULT_CODE);
    }

    public ValueCallback<Uri[]> getFilePathCallback() {
        return filePathCallback;
    }

    public void setFilePathCallback(ValueCallback<Uri[]> filePathCallback) {
        this.filePathCallback = filePathCallback;
    }

    public Uri getCameraTakePhotoTargetUri() {
        return cameraTakePhotoTargetUri;
    }
}
